<template>
  <div class="workorder-continue-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          icon="el-icon-arrow-left" 
          @click="goBack"
          class="back-button">
          返回
        </el-button>
        <div class="page-info">
          <h1 class="page-title">工单持续处理</h1>
          <p class="page-subtitle">工单编号：{{ workOrder.workOrderId }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-tag :type="statusClass" size="medium">{{ displayStatus }}</el-tag>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <div class="form-sections">
        
        <!-- 上一次处理信息（历史记录） - 仅在非第一次处理时显示 -->
        <div class="form-section" v-if="!isFirstTimeProcessing">
          <div class="section-header">
            <h3 class="section-title">上一次处理信息</h3>
            <div class="section-status complete">
              <i class="el-icon-time"></i>
              <span>历史记录</span>
            </div>
          </div>
          <div class="section-content">
            <PreviousProcessingInfo
              :processing-data="previousProcessing"
              :manual-data="previousManual"
              :user-list="userList"
              class="form-component"
            />
          </div>
        </div>

        <!-- 当前处理信息 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">当前处理信息</h3>
            <div class="section-status" :class="{ 'complete': processingInfoComplete }">
              <i class="el-icon-check" v-if="processingInfoComplete"></i>
              <i class="el-icon-warning" v-else></i>
              <span>{{ processingInfoProgress.filled }}/{{ processingInfoProgress.total }} {{ processingInfoComplete ? '已完成' : '未完成' }}</span>
            </div>
          </div>
          <div class="section-content">
            <ProcessingInfoForm
              :form-data="workOrder"
              :date-picker-options="datePickerOptions"
              :user-list="userList"
              :compact="true"
              class="form-component"
            />
          </div>
        </div>

        <!-- 当前现场确认 -->
        <div class="form-section">
          <div class="section-header">
            <h3 class="section-title">当前现场确认</h3>
            <div class="section-status" :class="{ 'complete': fieldConfirmationComplete }">
              <i class="el-icon-check" v-if="fieldConfirmationComplete"></i>
              <i class="el-icon-warning" v-else></i>
              <span>{{ fieldConfirmationProgress.filled }}/{{ fieldConfirmationProgress.total }} {{ fieldConfirmationComplete ? '已完成' : '未完成' }}</span>
            </div>
          </div>
          <div class="section-content">
            <ManualInputForm
              ref="manualInputForm"
              :form-data="workOrder"
              :compact="true"
              class="form-component"
            />
          </div>
        </div>

      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button @click="saveDraft" :loading="saving">保存草稿</el-button>
        <el-button 
          type="primary" 
          @click="submitContinue" 
          :loading="submitting"
          :disabled="!canSubmit">
          提交处理结果
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import ProcessingInfoForm from './components/ProcessingInfoForm.vue';
import ManualInputForm from './components/ManualInputForm.vue';
import PreviousProcessingInfo from './components/PreviousProcessingInfo.vue';
import { parseTime } from '@/utils/ruoyi';

// 导入API函数
import { getOrderDetail, updateOrder } from '@/api/fault/order';
import { addProcess } from '@/api/fault/process';
import { listUser } from '@/api/system/user'; // 引入获取用户列表的接口

export default {
  name: 'WorkOrderContinue',
  dicts: ['gelly_abnormal_type', 'gelly_fault_level', 'gelly_acceptance_result'],
  components: {
    ProcessingInfoForm,
    ManualInputForm,
    PreviousProcessingInfo
  },
  data() {
    return {
      orderId: null, // 存储实际的工单ID（数据库ID）
      handlingProcesses: [], // 存储历史处理记录
      userList: [], // 用户列表
      datePickerOptions: {
        shortcuts: [
          { text: '今天', onClick(picker) { picker.$emit('pick', new Date()); } },
          { text: '明天', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 24); picker.$emit('pick', d); } },
          { text: '一周后', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 24 * 7); picker.$emit('pick', d); } }
        ]
      },
      workOrder: {
        workOrderId: '', // 工单编号（显示用）
        handler: '',
        handlerId: null, // 处理人员ID
        estimatedTime: '',
        solution: '',
        onSiteObservation: '',
        productionPart: '',
        acceptanceResult: '',
        processingStatus: '处理中'
      },
      previousProcessing: {
        handler: '',
        estimatedTime: '',
        solution: '',
        onSiteObservation: '',
        processedTime: '',
        processingNotes: ''
      },
      previousManual: {
        productionPart: '',
        onSiteObservation: '',
        acceptanceResult: '',
        completedTime: '',
        inspector: ''
      },
      saving: false,
      submitting: false,
      datePickerOptions: {
        shortcuts: [
          { text: '1小时后', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000); picker.$emit('pick', d); } },
          { text: '4小时后', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 4); picker.$emit('pick', d); } },
          { text: '明天', onClick(picker) { const d = new Date(); d.setTime(d.getTime() + 3600 * 1000 * 24); picker.$emit('pick', d); } }
        ]
      }
    }
  },
  computed: {
    // 判断是否是第一次处理
    isFirstTimeProcessing() {
      // 如果没有历史处理记录，则为第一次处理
      return !this.handlingProcesses || this.handlingProcesses.length === 0;
    },
    displayStatus() {
      const statusMap = {
        '处理中': '处理中',
        '已完成': '已完成',
        '待处理': '待处理'
      };
      return statusMap[this.workOrder.processingStatus] || '处理中';
    },
    statusClass() {
      const classMap = {
        '处理中': 'warning',
        '已完成': 'success',
        '待处理': 'info'
      };
      return classMap[this.workOrder.processingStatus] || 'warning';
    },

    // 当前处理信息完成状态
    processingInfoComplete() {
      return this.processingInfoProgress.filled === this.processingInfoProgress.total;
    },

    // 当前处理信息进度
    processingInfoProgress() {
      let filled = 0, total = 4;
      if (this.workOrder.handler) filled++;
      if (this.workOrder.estimatedTime) filled++;
      if (this.workOrder.solution) filled++;
      if (this.workOrder.onSiteObservation) filled++;
      return { filled, total };
    },

    // 现场确认完成状态
    fieldConfirmationComplete() {
      return this.fieldConfirmationProgress.filled === this.fieldConfirmationProgress.total;
    },

    // 现场确认进度（生产零件 + 验收结果）
    fieldConfirmationProgress() {
      let filled = 0, total = 2;
      if (this.workOrder.productionPart) filled++;
      if (this.workOrder.acceptanceResult !== undefined && this.workOrder.acceptanceResult !== null && this.workOrder.acceptanceResult !== '') filled++;
      return { filled, total };
    },
    canSubmit() {
      return this.processingInfoComplete && this.fieldConfirmationComplete;
    }
  },
  created() {
    this.fetchUserList(); // 获取用户列表
    this.loadWorkOrderData();
  },
  methods: {
    async fetchUserList() {
      try {
        const response = await listUser({ pageNum: 1, pageSize: 9999 }); // 传递分页参数获取所有用户
        if (response.code === 200) {
          this.userList = response.rows.map(user => ({
            label: user.userName, // 使用用户名作为显示
            value: user.userId // 使用userId作为ID
          }));
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
      }
    },
    loadWorkOrderData() {
      // 从路由参数获取工单ID和其他信息
      const workOrderId = this.$route.params.id;
      const queryParams = this.$route.query;

      // 设置工单ID，如果没有传递则使用默认值
      this.workOrder.workOrderId = workOrderId || 'WO-DEFAULT-' + Date.now();

      // 如果有查询参数，使用这些信息
      if (queryParams.id) {
        console.log('从工单列表跳转，工单ID:', queryParams.id);
        console.log('工单编号:', queryParams.orderNumber);
        // 这里应该调用API根据工单ID加载完整的工单数据
        this.loadWorkOrderFromAPI(queryParams.id);
      } else {
        // 没有传递数据时，设置默认的工单信息
        this.setDefaultWorkOrderData();
      }

      // 加载历史处理记录
      this.loadPreviousProcessingData();
    },

    // 从API加载工单数据
    async loadWorkOrderFromAPI(orderId) {
      try {
        console.log('加载工单数据，ID:', orderId);
        this.orderId = orderId;

        // 调用API获取工单详细信息
        const response = await getOrderDetail(orderId); // 确保getOrderDetail实现为/fault/order/details/ + id

        if (response.code === 200 && response.data) {
          const orderData = response.data;
          console.log('获取到的工单数据:', orderData);
          console.log('工单状态 orderStatus:', orderData.orderStatus);

          // 更新工单基础信息
          this.workOrder = {
            ...this.workOrder,
            workOrderId: orderData.orderNumber,
            processingStatus: this.getStatusText(orderData.orderStatus)
          };

          console.log('设置的 processingStatus:', this.workOrder.processingStatus);

          // 如果工单状态是"待处理"，立即更新为"处理中"
          if (orderData.orderStatus === 0) {
            console.log('检测到待处理状态，立即更新为处理中...');
            await this.updateOrderStatusToProcessing();
          }

          // 故障分析数据仅作为参考，不自动填充到处理方案中
          // 让用户根据实际情况填写具体的处理方案

          // 存储历史处理记录
          this.handlingProcesses = orderData.handlingProcesses || [];

          // 如果有处理过程数据，检查最新处理结果
          if (orderData.handlingProcesses && orderData.handlingProcesses.length > 0) {
            const latestProcess = orderData.handlingProcesses[orderData.handlingProcesses.length - 1];

            // 检查最新处理的验收结果
            console.log('最新处理记录:', latestProcess);
            console.log('最新验收结果:', latestProcess.acceptanceResult);

            // 如果最新处理的验收结果是通过(1)，工单应该已完成
            if (latestProcess.acceptanceResult === 1) {
              this.$message.warning('该工单已验收通过并完成，无需继续处理');
              // 可以选择跳转回工单列表或显示只读视图
              setTimeout(() => {
                this.$router.push('/gelly/order');
              }, 2000);
              return;
            }

            // 如果验收结果是待复检(0)或不通过(2)，则可以继续处理
            // 不要预填充上次的数据，让用户重新填写具体的处理方案
            console.log('验收未通过，可以继续处理');
            // affectedAxes兼容解析
            if (orderData.affectedAxes) {
              this.workOrder.affectedAxis = orderData.affectedAxes.replace(/"/g, '').split(',').map(s => s.trim());
            }

            // 显示最新的处理信息作为上一次处理记录
            if (this.handlingProcesses.length > 0) {
              const latestProcess = this.handlingProcesses[this.handlingProcesses.length - 1];
              this.previousProcessing = {
                handler: latestProcess.handlerId,
                estimatedTime: latestProcess.estimatedCompletionTime,
                solution: orderData.faultAnalysis?.solution || '',
                onSiteObservation: latestProcess.handlingNotes,
                processedTime: latestProcess.createTime,
                processingNotes: latestProcess.handlingScheme
              };
              this.previousManual = {
                productionPart: latestProcess.producedParts,
                onSiteObservation: latestProcess.handlingNotes,
                acceptanceResult: latestProcess.acceptanceResult,
                completedTime: latestProcess.actualCompletionTime || latestProcess.createTime,
                inspector: latestProcess.handlerId
              };
            }
          }

          this.$message.success('工单数据加载成功');
        } else {
          throw new Error(response.msg || '获取工单数据失败');
        }
      } catch (error) {
        console.error('加载工单数据失败:', error);
        this.$message.error('加载工单数据失败: ' + (error.message || '未知错误'));
        // 加载失败时也设置默认数据
        this.setDefaultWorkOrderData();
      }
    },

    // 更新工单状态为处理中
    async updateOrderStatusToProcessing() {
      try {
        const updateData = {
          id: this.orderId,
          orderStatus: 1 // 处理中
        };
        console.log('更新工单状态为处理中，数据:', updateData);

        const response = await updateOrder(updateData);
        console.log('状态更新响应:', response);

        if (response.code === 200) {
          console.log('工单状态已成功更新为处理中');
          // 更新本地显示状态
          this.workOrder.processingStatus = '处理中';
          this.$message.success('工单已进入处理状态');
        } else {
          throw new Error(response.msg || '状态更新失败');
        }
      } catch (error) {
        console.error('更新工单状态失败:', error);
        this.$message.warning('状态更新失败: ' + (error.message || '未知错误'));
      }
    },

    // 将数字状态转换为文本
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '处理中',
        2: '已完成'
      };
      return statusMap[status] || '处理中';
    },

    // 设置默认工单数据（当没有传递数据时）
    setDefaultWorkOrderData() {
      console.log('设置默认工单数据');

      // 设置基本的默认值，确保页面能正常显示
      this.workOrder = {
        ...this.workOrder,
        handler: '',
        handlerId: null,
        estimatedTime: '',
        solution: '',
        onSiteObservation: '',
        productionPart: '',
        acceptanceResult: '',
        processingStatus: '处理中'
      };

      this.$message.info('未传递工单数据，已加载默认模板');
    },
    loadPreviousProcessingData() {
      // 检查是否有工单ID，如果没有则使用默认数据
      const hasWorkOrderId = this.workOrder.workOrderId && !this.workOrder.workOrderId.includes('DEFAULT');

      if (hasWorkOrderId) {
        // 有真实工单ID时，模拟加载实际数据
        this.previousProcessing = {
          handler: '张工',
          estimatedTime: '2025-07-14 16:00:00',
          solution: '初步检查发现轴承异响，需要更换轴承。已订购配件，预计明天到货。',
          onSiteObservation: '设备运行时X轴有明显异响，初步判断为轴承磨损。已停机等待配件。',
          processedTime: '2025-07-14 14:30:00',
          processingNotes: '配件已订购，等待到货后继续处理'
        };

        this.previousManual = {
          productionPart: '齿轮箱体',
          onSiteObservation: '设备异响明显，已停机。生产线暂停，等待维修完成。',
          acceptanceResult: '待复检',
          completedTime: '2025-07-14 15:00:00',
          inspector: 2 // 使用用户ID，会通过getUserName映射为用户名
        };
      } else {
        // 没有真实工单ID时，使用示例数据
        this.previousProcessing = {
          handler: '示例处理人',
          estimatedTime: '2025-07-14 16:00:00',
          solution: '这是一个示例处理方案，用于展示工单持续处理页面的功能。',
          onSiteObservation: '这是示例的现场观察记录，用于演示页面布局和功能。',
          processedTime: '2025-07-14 14:30:00',
          processingNotes: '这是示例数据，实际使用时会显示真实的处理记录'
        };

        this.previousManual = {
          productionPart: '示例零件',
          onSiteObservation: '这是示例的现场观察记录，用于演示页面功能。',
          acceptanceResult: '待复检',
          completedTime: '2025-07-14 15:00:00',
          inspector: '示例验收人'
        };
      }
    },
    goBack() {
      this.$router.go(-1);
    },

    // 格式化日期时间为API所需的格式
    formatDateTime(dateTime) {
      if (!dateTime) return null;

      // 如果是字符串，尝试解析
      if (typeof dateTime === 'string') {
        const date = new Date(dateTime);
        if (isNaN(date.getTime())) {
          return null;
        }
        return date.toISOString().slice(0, 19).replace('T', ' ');
      }

      // 如果是Date对象
      if (dateTime instanceof Date) {
        return dateTime.toISOString().slice(0, 19).replace('T', ' ');
      }

      return null;
    },

    // 验证处理数据
    validateProcessData(data) {
      if (!data.handlingScheme || data.handlingScheme.trim() === '') {
        throw new Error('处理方案不能为空');
      }

      if (!data.estimatedCompletionTime) {
        throw new Error('预计完成时间不能为空');
      }

      if (!data.handlingNotes || data.handlingNotes.trim() === '') {
        throw new Error('处理记录不能为空');
      }

      return true;
    },
    async saveDraft() {
      this.saving = true;
      try {
        // 调用API保存草稿
        await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟API调用
        this.$message.success('草稿保存成功');
      } catch (error) {
        this.$message.error('保存失败，请重试');
      } finally {
        this.saving = false;
      }
    },
    async submitContinue() {
      if (!this.canSubmit) {
        this.$message.warning('请完成所有必填信息');
        return;
      }

      if (!this.orderId) {
        this.$message.error('工单ID不存在，无法提交');
        return;
      }

      this.submitting = true;
      try {
        // 注意：工单状态已在页面加载时更新为"处理中"，这里不需要重复更新

        // 准备处理过程数据
        console.log('当前工单数据:', this.workOrder);
        console.log('选择的处理人员名称:', this.workOrder.handler);
        console.log('选择的处理人员ID:', this.workOrder.handlerId);

        const processData = {
          orderId: this.orderId,
          handlerId: this.workOrder.handlerId || this.$store.getters.userId || 1, // 使用用户选择的处理人员ID
          handlingScheme: this.workOrder.solution || '',
          estimatedCompletionTime: this.formatDateTime(this.workOrder.estimatedTime),
          handlingNotes: this.workOrder.onSiteObservation || '',
          producedParts: this.workOrder.productionPart || '',
          acceptanceResult: Number(this.workOrder.acceptanceResult)
        };

        // 验证数据
        this.validateProcessData(processData);

        // 调用API提交处理结果
        const response = await addProcess(processData);

        if (response.code === 200) {
          this.$message.success('处理结果提交成功');

          // 根据验收结果决定工单状态
          let newOrderStatus = 1; // 默认为处理中
          let statusMessage = '';

          if (this.workOrder.acceptanceResult === 1) {
            // 验收通过，工单完成
            newOrderStatus = 2; // 已完成
            statusMessage = '验收通过，工单已完成';
          } else if (this.workOrder.acceptanceResult === 0 || this.workOrder.acceptanceResult === 2) {
            // 待复检或不通过，工单继续处理中
            newOrderStatus = 1; // 处理中
            statusMessage = '验收未通过，工单将继续处理';
          }

          // 更新工单状态
          try {
            const finalUpdateData = {
              id: this.orderId,
              orderStatus: newOrderStatus
            };
            console.log('最终状态更新数据:', finalUpdateData);

            const finalUpdateResponse = await updateOrder(finalUpdateData);
            console.log('最终状态更新响应:', finalUpdateResponse);

            if (finalUpdateResponse.code === 200) {
              this.$message.success(statusMessage);
              // 更新本地状态显示
              this.workOrder.processingStatus = newOrderStatus === 2 ? '已完成' : '处理中';
            } else {
              throw new Error(finalUpdateResponse.msg || '最终状态更新失败');
            }
          } catch (updateError) {
            console.error('更新工单状态失败:', updateError);
            this.$message.warning('处理结果已提交，但状态更新失败');
          }

          // 跳转到工单列表
          setTimeout(() => {
            this.$router.push('/gelly/order');
          }, 1500);
        } else {
          throw new Error(response.msg || '提交失败');
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error('提交失败: ' + (error.message || '请重试'));
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

<style scoped>
/* 页面布局 */
.workorder-continue-page {
  min-height: 100vh;
  background: #f8fafc;
}

.page-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  border: none;
  background: #f3f4f6;
  color: #6b7280;
}

.back-button:hover {
  background: #e5e7eb;
  color: #374151;
}

.page-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.content-wrapper {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.form-sections {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 32px;
}

.form-section {
  background: white;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  border: none;
}

.section-header {
  padding: 16px 24px 12px;
  border-bottom: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  letter-spacing: -0.01em;
}

.section-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 16px;
  transition: all 0.3s ease;
}

.section-status:not(.complete) {
  background: #fef3cd;
  color: #92400e;
  border: 1px solid #fbbf24;
}

.section-status.complete {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #10b981;
}

.section-content {
  padding: 0 24px 24px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 24px 0;
}

.action-buttons .el-button {
  padding: 12px 32px;
  border-radius: 8px;
  font-weight: 500;
}
</style>
